package com.lepu.app.fun.chat.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.utils.LoginUtil;
import com.app.utils.SdLocal;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragment;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.ImageCompressUtils;
import com.core.lib.utils.RecordMediaUtil;
import com.core.lib.utils.geneal.UploadMenuImage;
import com.core.lib.utils.main.FileUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.SdUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.photo.AppPhotoGridActivity;
import com.core.lib.utils.photo.PhotoInfo;
import com.lepu.app.fun.chat.activity.ChatMainActivity;
import com.lepu.app.fun.chat.activity.GroupMembersActivity;
import com.lepu.app.fun.chat.bean.BeanLectureChatUser;
import com.lepu.app.fun.chat.bean.ChatSession;
import com.lepu.app.fun.chat.util.ChatSendListener;
import com.lepu.app.fun.chat.util.VoicePlayClickListener;
import com.lepu.app.fun.chat.util.VoicePlayClickListenerRoomMessage;
import com.lepu.app.main.permission.PermissionUtil;
import com.lepu.app.main.permission.callback.PermissionResultCallBack;
import com.lepu.app.widget.MentionEditText;
import com.lepu.pasm.R;

public class ChatFragmentBase extends BaseFragment implements
		OnScrollListener,SensorEventListener,MentionEditText.OnMentionInputListener {

	private static final int REQUEST_CODE_AT = 1000;
	private static final int RECORD_TIMES_VALUE = 60;//允许录音60秒
	// ===========================================
	View mView = null;
	SwipeRefreshLayout mRefreshLayout = null;
	public static ListView mDataListview = null;
	LinearLayout mChatRecordStateLayout = null;
	ImageView mChatYuyinRecordImageView = null;
	TextView mChatYuyinRecordTextView = null;

	LinearLayout mTopRightTipLayout = null;
	TextView mTopRightTipTextView = null;

	LinearLayout mBottomRightTipLayout = null;
	TextView mBottomRightTipTextView = null;

	// left
	ImageView mChatYuyinTextSwitchImageView = null;// 语音 文本发送切换

	// center
	ImageView mChatYuyinBtnSendSwitchImageView = null;// 语音按钮
	MentionEditText mChatContentEditText = null;// 输入内容

	// right
	ImageView mChatAddOtherImageView = null;// add
	Button mChatContentSendButton = null;// send

	// bottom
	LinearLayout mChatInputLayout = null;
	LinearLayout mChatAddOtherLayout = null;// add other
	TextView mChatAddOtherPhotoTextView = null;// photo
	TextView mChatAddOtherCameraTextView = null;// camera

	private Drawable[] mChatRecordAnimArray = null;

	BaseFragmentActivity mBaseFragmentActivity = null;

	private PowerManager.WakeLock mWakeLock;
	private String mAudioFilePath = "";

	// 是否可以发送文件
	boolean mNeedSendFile = false;//语音 图片 照相
	boolean mNeedSendSound = true;//支持发文件的同时，可以选择性的选择是否可以发语音
	boolean mNeedChatSend = true;//聊天输入框是否显示
	boolean mIsGroupChat = false;//是否是群聊

	ChatSendListener mChatSendListener = null;
	private Timer mRecordTimer = null;
	private int mRecordTime = 0;
	private boolean mCanSendSound = true;//是否已经发送了语音
	private boolean mEnterRecordDaoJiShi = false;

	private SensorManager mSensorManager;
	private Sensor mSensor;

	String mGroupID = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		init();
		return mView;
	}

	@Override
	public void onResume() {
		super.onResume();

		// 发送多张图片，监听
		updateAddPhotos();

		mSensorManager.registerListener(this, mSensor,
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	public void onPause() {
		super.onPause();

		mSensorManager.unregisterListener(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		stopRecordTimer();
		mDataListview = null;
	}

	/*
	 * 初始化ui控件，不要初始化数据！！！！
	 * 
	 * 初始化控件，需要用mMainView.findViewById 不能使用findViewById，否则程序会闪退的
	 */
	@SuppressWarnings("deprecation")
	private void init() {
		mBaseFragmentActivity = (BaseFragmentActivity) getActivity();

		mSensorManager = (SensorManager) mBaseFragmentActivity.getSystemService(Context.SENSOR_SERVICE);
		mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

		mRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipeLayout);
		mRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);

		mChatRecordAnimArray = new Drawable[] {
				getResources().getDrawable(R.drawable.record_animate_01),
				getResources().getDrawable(R.drawable.record_animate_02),
				getResources().getDrawable(R.drawable.record_animate_03),
				getResources().getDrawable(R.drawable.record_animate_04),
				getResources().getDrawable(R.drawable.record_animate_05),
				getResources().getDrawable(R.drawable.record_animate_06),
				getResources().getDrawable(R.drawable.record_animate_07),
				getResources().getDrawable(R.drawable.record_animate_08),
				getResources().getDrawable(R.drawable.record_animate_09),
				getResources().getDrawable(R.drawable.record_animate_10),
				getResources().getDrawable(R.drawable.record_animate_11),
				getResources().getDrawable(R.drawable.record_animate_12),
				getResources().getDrawable(R.drawable.record_animate_13),
				getResources().getDrawable(R.drawable.record_animate_14) };

		mWakeLock = ((PowerManager) mBaseFragmentActivity
				.getSystemService(Context.POWER_SERVICE)).newWakeLock(
				PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");

		mDataListview = (ListView) mView.findViewById(R.id.dataListview);
		mChatRecordStateLayout = (LinearLayout) mView
				.findViewById(R.id.chatRecordStateLayout);
		mChatYuyinRecordImageView = (ImageView) mView
				.findViewById(R.id.chatYuyinRecordImageView);
		mChatYuyinRecordTextView = (TextView) mView
				.findViewById(R.id.chatYuyinRecordTextView);

		// left
		mChatYuyinTextSwitchImageView = (ImageView) mView
				.findViewById(R.id.chatYuyinTextSwitchImageView);

		// center
		mChatYuyinBtnSendSwitchImageView = (ImageView) mView
				.findViewById(R.id.chatYuyinBtnSendSwitchImageView);
		mChatContentEditText = (MentionEditText) mView
				.findViewById(R.id.chatContentEditText);
		//new EmojiFilter(),
		mChatContentEditText.setFilters(new InputFilter[]{
				new InputFilter.LengthFilter(1000)});
		mChatContentEditText.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// bottom
				addOtherLayoutHide();
				return false;
			}
		});
		mChatContentEditText.mCanMention = mIsGroupChat;
		mChatContentEditText.setOnMentionInputListener(this);

		// right
		mChatAddOtherImageView = (ImageView) mView
				.findViewById(R.id.chatAddOtherImageView);
		mChatContentSendButton = (Button) mView
				.findViewById(R.id.chatContentSendButton);

		// bottom send file
		mChatInputLayout = (LinearLayout) mView.findViewById(R.id.chatInputLayout);
		mChatAddOtherLayout = (LinearLayout) mView
				.findViewById(R.id.chatAddOtherLayout);
		mChatAddOtherPhotoTextView = (TextView) mView
				.findViewById(R.id.chatAddOtherPhotoTextView);
		mChatAddOtherCameraTextView = (TextView) mView
				.findViewById(R.id.chatAddOtherCameraTextView);

		mChatRecordStateLayout.setVisibility(View.GONE);
		if (mNeedSendFile) {
			// left
			if(mNeedSendSound)
			{
				mChatYuyinTextSwitchImageView.setVisibility(View.VISIBLE);
			}

			// center
			mChatYuyinBtnSendSwitchImageView.setVisibility(View.GONE);
			mChatContentEditText.setVisibility(View.VISIBLE);

			// right
			mChatAddOtherImageView.setVisibility(View.VISIBLE);
			mChatAddOtherLayout.setVisibility(View.GONE);
			mChatContentSendButton.setVisibility(View.GONE);
		} else {
			// left
			mChatYuyinTextSwitchImageView.setVisibility(View.GONE);

			// center
			mChatYuyinBtnSendSwitchImageView.setVisibility(View.GONE);
			mChatContentEditText.setVisibility(View.VISIBLE);

			// right
			mChatAddOtherImageView.setVisibility(View.GONE);
			mChatAddOtherLayout.setVisibility(View.GONE);
			mChatContentSendButton.setVisibility(View.VISIBLE);
		}

		mChatYuyinTextSwitchImageView.setOnClickListener(mOnClickListener);
		mChatYuyinBtnSendSwitchImageView
				.setOnTouchListener(new PressToSpeakListen());//
		mChatAddOtherImageView.setOnClickListener(mOnClickListener);
		mChatContentSendButton.setOnClickListener(mOnClickListener);
		mChatAddOtherPhotoTextView.setOnClickListener(mOnClickListener);
		mChatAddOtherCameraTextView.setOnClickListener(mOnClickListener);

		mDataListview.setOnScrollListener(this);

		mTopRightTipLayout = (LinearLayout) mView.findViewById(R.id.topRightTipLayout);
		mTopRightTipLayout.setVisibility(View.GONE);
		mTopRightTipTextView = (TextView) mView.findViewById(R.id.topRightTipTextView);

		mBottomRightTipLayout = (LinearLayout) mView.findViewById(R.id.bottomRightTipLayout);
		mBottomRightTipLayout.setVisibility(View.GONE);
		mBottomRightTipTextView = (TextView) mView.findViewById(R.id.bottomRightTipTextView);
	}

	public void scrollBottom() {
//		new Handler().post(new Runnable() {
//
//			@Override
//			public void run() {
//				mDataListview.setSelection(mDataListview.getCount() - 1);
//			}
//		});
//
//		mDataListview.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		mDataListview.setSelection(mDataListview.getCount() - 1);
		mDataListview.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

		clearBottomRightTip();
	}

	private void updateAddPhotos() {
		if (AppPhotoGridActivity.mSelectList.size() > 0) {
			ArrayList<String> photoFileList = new ArrayList<String>();
			for (PhotoInfo item : AppPhotoGridActivity.mSelectList) {

				String srcPath = item.getPath_absolute();

				try {
					String endPath = SdLocal.getChatImagePath(getActivity(),
							LoginUtil.getUserId(),
							String.valueOf(System.currentTimeMillis()));
					ImageCompressUtils.CompressImageFile(srcPath, endPath);
					photoFileList.add(endPath);
				} catch (Exception e) {
					e.printStackTrace();
				} catch (OutOfMemoryError e) {
					e.printStackTrace();
				}
			}

			if (photoFileList.size() != AppPhotoGridActivity.mSelectList.size()) {
				LogUtilBase.LogD(null, "发送多张图片，有压缩失败的");
			}

			if (mChatSendListener != null) {
				mChatSendListener.sendPhotos(photoFileList);
			}
		}

		if (AppPhotoGridActivity.mSelectList != null) {
			AppPhotoGridActivity.mSelectList.clear();
		}
	}

	View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			int rid = v.getId();
			switch (rid) {
			// left
			case R.id.chatYuyinTextSwitchImageView:

				checkAudioSendPermission(v);

				break;
			// center
			case R.id.chatYuyinBtnSendSwitchImageView:
				// send yuyin
				// to do

				break;
			// right
			case R.id.chatAddOtherImageView:
				v.setSelected(!v.isSelected());

				if (v.isSelected()) {
					// bottom
					mChatAddOtherLayout.setVisibility(View.VISIBLE);
				} else {
					// bottom
					mChatAddOtherLayout.setVisibility(View.GONE);
				}
				UtilityBase.closeSoftInput(getActivity());
				break;
			case R.id.chatContentSendButton:
				// send content
				String content = mChatContentEditText.getText().toString()
						.trim();

				if (TextUtils.isEmpty(content)) {
					UIHelper.showToast(getActivity(), "请输入内容");
					return;
				}

				if(content.length() > 1000){
					UIHelper.showToast(getActivity(), "请输入1000字以内");
					return;
				}

				if (mChatSendListener != null) {
					mChatSendListener.sendText(content);
				}
				break;
			// bottom
			case R.id.chatAddOtherPhotoTextView:
				// send photo
				String tempCamera = SdLocal.getTempPhotoPath(
						mBaseFragmentActivity, "temp_camera_icon");
				UploadMenuImage.getInstance(ChatFragmentBase.this).setFilePath(
						tempCamera);
				UploadMenuImage.getInstance(ChatFragmentBase.this).setIsCut(
						false);
				UploadMenuImage.getInstance(ChatFragmentBase.this)
						.setIsPhotoDouble(true);
				UploadMenuImage.getInstance(ChatFragmentBase.this)
						.setPhotoDoubleNum(9);
				UploadMenuImage.getInstance(ChatFragmentBase.this).jumpPhoto();
				break;
			case R.id.chatAddOtherCameraTextView:
				// send camera
				String tempCamera2 = SdLocal.getTempPhotoPath(
						mBaseFragmentActivity, "temp_camera_icon");
				UploadMenuImage.getInstance(ChatFragmentBase.this).setFilePath(
						tempCamera2);
				UploadMenuImage.getInstance(ChatFragmentBase.this).setIsCut(
						false);
				UploadMenuImage.getInstance(ChatFragmentBase.this)
						.setIsPhotoDouble(true);
				UploadMenuImage.getInstance(ChatFragmentBase.this)
						.setPhotoDoubleNum(9);
				UploadMenuImage.getInstance(ChatFragmentBase.this).jumpCamera();
				break;
			default:
				break;
			}
		}
	};

	public void addOtherLayoutHide()
	{
		ImageView chatAddOtherImageView = (ImageView) mView.findViewById(R.id.chatAddOtherImageView);
		if(chatAddOtherImageView.isSelected()){
			chatAddOtherImageView.setSelected(false);
			mChatAddOtherLayout.setVisibility(View.GONE);
			mChatContentEditText.requestFocus();
		}

	}

	/**
	 * 相机回调监听
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode,
			final Intent data) {

		if (resultCode == Activity.RESULT_OK) {
			if(requestCode == REQUEST_CODE_AT){

				if(data != null && data.getExtras() != null){
					BeanLectureChatUser item = (BeanLectureChatUser) data.getSerializableExtra("BeanLectureChatUser");
					if(item != null)
					{
						int index = mChatContentEditText.getSelectionStart();
						Editable editable = mChatContentEditText.getText();
						editable.delete(index-1, index);

						int UserID = UtilityBase.parseInt(item.UserID);
						mChatContentEditText.mentionUser(UserID,item.NickName,true);

						UtilityBase.openSoftInput(getActivity());
					}
				}
			}
			else if (requestCode == 100) {
				// int index = data.getExtras().getInt("index");
				// removeImage(index);
			} else {
				UploadMenuImage.getInstance(this).onActivityResult(
						new CallBack() {
							@Override
							public void callBackSuccess(Object obj) {
								super.callBackSuccess(obj);

								// 只有照相回调回来，
								String tempPath = SdLocal.getTempPhotoPath(
										mBaseFragmentActivity,
										"temp_camera_icon");

								String filePath = SdLocal.getChatImagePath(
										mBaseFragmentActivity, LoginUtil
												.getUserId(), String
												.valueOf(System
														.currentTimeMillis()));

								try {
									ImageCompressUtils.CompressImageFile(
											tempPath, filePath);

									// 删除照相临时文件
									File tempCameraFile = new File(tempPath);
									if (tempCameraFile.exists()) {
										FileUtilBase.deleteFile(tempCameraFile);
									}

									if (mChatSendListener != null) {
										mChatSendListener.sendPhoto(filePath);

									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}, requestCode, resultCode, data);
			}
		}
	};

	// ======================================
	@SuppressLint("HandlerLeak")
	private Handler mMicImageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			mChatYuyinRecordImageView.setImageDrawable(mChatRecordAnimArray[msg.what]);
		}
	};

	private void showHideVoiceState(boolean isShow, boolean selected) {
		if (isShow) {
			mChatRecordStateLayout.setVisibility(View.VISIBLE);
		} else {
			mChatRecordStateLayout.setVisibility(View.GONE);
		}

		if (selected) {
			mChatYuyinRecordTextView.setText(R.string.move_up_to_cancel);
			mChatYuyinRecordTextView.setBackgroundColor(Color.TRANSPARENT);
		} else {
			mChatYuyinRecordTextView.setText(R.string.release_to_cancel);
			mChatYuyinRecordTextView
					.setBackgroundResource(R.drawable.recording_text_hint_bg);
		}
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
//		float range = event.values[0];
//		if (range == mSensor.getMaximumRange()) {
//			LogUtilBase.LogD(null,"正常模式");
//
//			VoicePlayClickListener voicePlayClickListener = VoicePlayClickListener.currentPlayListener;
//			if(voicePlayClickListener != null)
//			{
//				voicePlayClickListener.setSpeakerphoneOn(true);
//			}
//
//			VoicePlayClickListenerRoomMessage voicePlayClickListenerRoom = VoicePlayClickListenerRoomMessage.currentPlayListener;
//			if(voicePlayClickListenerRoom != null)
//			{
//				voicePlayClickListenerRoom.setSpeakerphoneOn(true);
//			}
//		} else {
//			LogUtilBase.LogD(null, "听筒模式");
//
//			VoicePlayClickListener voicePlayClickListener = VoicePlayClickListener.currentPlayListener;
//			if(voicePlayClickListener != null)
//			{
//				voicePlayClickListener.setSpeakerphoneOn(false);
//			}
//
//			VoicePlayClickListenerRoomMessage voicePlayClickListenerRoom = VoicePlayClickListenerRoomMessage.currentPlayListener;
//			if(voicePlayClickListenerRoom != null)
//			{
//				voicePlayClickListenerRoom.setSpeakerphoneOn(false);
//			}
//		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	private void stopVoice()
	{
		VoicePlayClickListener voicePlayClickListener = VoicePlayClickListener.currentPlayListener;
		if(voicePlayClickListener != null)
		{
			voicePlayClickListener.stopPlayVoice();
		}

		VoicePlayClickListenerRoomMessage voicePlayClickListenerRoomMessage = VoicePlayClickListenerRoomMessage.currentPlayListener;
		if(voicePlayClickListenerRoomMessage != null)
		{
			voicePlayClickListenerRoomMessage.stopPlayVoice();
		}
	}

	private void goAt() {
		BaseFragmentActivity baseFragmentActivity = (BaseFragmentActivity) getActivity();
        Intent intent = new Intent(baseFragmentActivity, GroupMembersActivity.class);
        intent.putExtra("GroupID", mGroupID);
		startActivityForResult(intent, REQUEST_CODE_AT);
		baseFragmentActivity.overridePendingTransition(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}

	@Override
	public void onMentionCharacterInput() {

		if(mIsGroupChat){
			goAt();
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence charSequence, int index, int i1, int count) {

		String content = charSequence.toString();
		if (content.length() > 0) {
			mChatAddOtherImageView.setVisibility(View.GONE);
			mChatContentSendButton.setVisibility(View.VISIBLE);
		} else {
			mChatAddOtherImageView.setVisibility(View.VISIBLE);
			mChatContentSendButton.setVisibility(View.GONE);
		}
	}

	@Override
	public void afterTextChanged(Editable editable) {

	}

	/**
	 * 按住说话listener
	 * 
	 */
	class PressToSpeakListen implements View.OnTouchListener {
		@SuppressLint({ "ClickableViewAccessibility", "Wakelock" })
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:

				// 按下
				if (!SdUtilBase.checkSdCanUse()) {
					UIHelper.showToast(getActivity(), "语音需要sdcard支持！");
					return false;
				}

				stopVoice();

				mCanSendSound = true;

				try {
					showHideVoiceState(true, true);
					v.setSelected(true);
					mWakeLock.acquire();

					mAudioFilePath = SdLocal.getChatVoicePath(getActivity(),
							LoginUtil.getUserId(),
							String.valueOf(System.currentTimeMillis()));

					RecordMediaUtil instance = RecordMediaUtil.getInstance();
					instance.setMicImageHandler(mMicImageHandler);
					instance.start(mAudioFilePath);

					//开启监听录音
					startRecordTimer();
					
				} catch (Exception e) {
					e.printStackTrace();

					showHideVoiceState(false, true);
					v.setSelected(false);
					if (mWakeLock.isHeld())
						mWakeLock.release();

					UIHelper.showToast(getActivity(), "录音失败");
					stopRecordTimer();
					return false;
				}

				return true;
			case MotionEvent.ACTION_MOVE: {

				// 移动
				if(mEnterRecordDaoJiShi)
				{
					return false;
				}

				if(!mCanSendSound)
				{
					return false;
				}

				if (event.getY() < 0) {
					showHideVoiceState(true, false);
				} else {
					showHideVoiceState(true, true);
				}
				return false;
			}
			case MotionEvent.ACTION_UP:

				// 抬手
				if(mCanSendSound)
				{
					mCanSendSound = false;
					stopSound();

					if (event.getY() < 0) {
						// discard the recorded audio.
						RecordMediaUtil.getInstance().discardRecording();
					} else {
						// stop recording and send voice file
						sendSound();
					}
				}

				return false;
			default:
				return false;
			}
		}
	}

	private void stopSound()
	{
		stopRecordTimer();
		// 抬手
		mChatYuyinBtnSendSwitchImageView.setSelected(false);
		showHideVoiceState(false, false);

		if (mWakeLock.isHeld())
			mWakeLock.release();
	}

	private void sendSound()
	{
		File audioFile = new File(mAudioFilePath);

		int duration = RecordMediaUtil.getInstance().stopRecodingReturnTime();
		long fileLength = 0L;
		if (audioFile.exists()) {
			fileLength = audioFile.length();
		}

		if (fileLength > 0 && duration > 900) {
			if (mChatSendListener != null) {
				mChatSendListener.sendVoice(mAudioFilePath);
			}
		} else {
			UIHelper.showToast(getActivity(), "录音时间太短");
		}
	}

	public void clearBottomRightTip()
	{
		mBottomRightTipLayout.setVisibility(View.GONE);
		mBottomRightTipTextView.setText(String.valueOf(0));
		mBottomRightTipTextView.setTag(0);
	}
	
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		UtilityBase.closeSoftInput(getActivity());

		if(mIsGroupChat){
			if(Utils.checkListViewIsBottom(mDataListview)){
				mDataListview.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
				clearBottomRightTip();
			}else{
				mDataListview.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	//===========================================
	@SuppressLint("HandlerLeak")
	private Handler mRecordTimeHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			//还可以说话
			mRecordTime ++;
			LogUtilBase.LogD(null,"mRecordTime===>>"+mRecordTime);

			if(mRecordTime >= 50){
				mEnterRecordDaoJiShi = true;

				int value = RECORD_TIMES_VALUE - mRecordTime;
				mChatYuyinRecordTextView.setText(String.format("您还可以说话%d秒",value));

				if(mRecordTime > RECORD_TIMES_VALUE){//>=
					if(mCanSendSound)
					{
						mCanSendSound = false;
						stopSound();
						sendSound();
					}
				}
			}
		}
	};

	private void startRecordTimer()
	{
		LogUtilBase.LogD(null,"startRecordTimer");
		if (mRecordTimer == null) {
			mRecordTimer = new Timer();
			mRecordTimer.schedule(new TimerTask() {

				@Override
				public void run() {

					mRecordTimeHandler.sendEmptyMessage(1);
				}
			}, 0, 1000);
		}
	}

	private void stopRecordTimer()
	{
		LogUtilBase.LogD(null,"stopRecordTimer");
		if (mRecordTimer != null) {
			mRecordTimer.cancel();
			mRecordTimer.purge();
			mRecordTimer = null;
		}
		mRecordTime = 0;
		mEnterRecordDaoJiShi = false;
	}

	public void checkAudioSendPermission(final View v) {
		PermissionUtil.getInstance().request(mBaseFragmentActivity, new String[]{Manifest.permission.RECORD_AUDIO,
						Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,
						Manifest.permission.WRITE_EXTERNAL_STORAGE,},
				new PermissionResultCallBack() {
					@Override
					public void onPermissionGranted() {
						//
						boolean flag = Utils.checkAudioPermission();
						if (!flag) {
							UIHelper.showToast(mBaseFragmentActivity, R.string.permission_tip_record_audio);
							return;
						}

						v.setSelected(!v.isSelected());

						if (v.isSelected()) {
							// center
							mChatYuyinBtnSendSwitchImageView
									.setVisibility(View.VISIBLE);
							mChatContentEditText.setVisibility(View.GONE);
							UtilityBase.closeSoftInput(getActivity());

							// bottom
							mChatAddOtherLayout.setVisibility(View.GONE);
						} else {
							// center
							mChatYuyinBtnSendSwitchImageView.setVisibility(View.GONE);
							mChatContentEditText.setVisibility(View.VISIBLE);

							// bottom
							mChatAddOtherLayout.setVisibility(View.GONE);
						}
					}

					@Override
					public void onPermissionGranted(String... permissions) {
						if (permissions == null || permissions.length == 0) {
						}
					}

					@Override
					public void onPermissionDenied(String... permissions) {
						if (permissions != null) {
						}
					}

					@Override
					public void onRationalShow(String... permissions) {
						if (permissions != null) {
							UIHelper.showToast(mBaseFragmentActivity, R.string.permission_tip);
							PermissionUtil.openSettingActivity(mBaseFragmentActivity);
						}
					}
				});
	}

}
